package com.example.demo.juc;

import lombok.SneakyThrows;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 有三个线程分别打印A,B,C请用多线程实现并在屏幕上 打印
 */
public class test01 {

    final static Lock lock = new ReentrantLock();
    final static Condition conditionA = lock.newCondition();
    final static Condition conditionB = lock.newCondition();
    final static Condition conditionC = lock.newCondition();
    volatile static String now = "A";


    static class MyThreadPrintA implements Runnable {
        @SneakyThrows
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {

                try {
                    lock.lock();
                    while (!now.equals("A")) {
                        conditionA.await();
                    }
                    System.out.println(now);
                    now = "B";
                    conditionB.signal();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }
    }


    static class myThreadPrintB implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {

                try {
                    lock.unlock();
                    while (!now.equals("B")) {
                        conditionB.await();
                    }
                    System.out.println(now);
                    now = "C";
                    conditionC.signal();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }
    }

    static class MyThreadPrintc implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {

                try {
                    lock.lock();
                    while (!now.equals("C")) {
                        conditionC.await();
                    }
                    System.out.println(now);
                    now = "A";
                    conditionA.signal();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }

            }
        }
    }

    public static void main(String[] args) {
        MyThreadPrintA myThreadPrintA = new MyThreadPrintA();
        myThreadPrintB myThreadPrintB = new myThreadPrintB();
        MyThreadPrintc myThreadPrintC = new MyThreadPrintc();

        Thread t1 = new Thread(myThreadPrintA);
        Thread t2 = new Thread(myThreadPrintB);
        Thread t3 = new Thread(myThreadPrintC);

        t1.start();
        t2.start();
        t3.start();

    }
}
